<?php

namespace App\Http\Controllers;

use App\User;
use App\Services\OSS;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * 获取user信息
     *
     * @param  Request
     * @return Response
     */
    public function infoUser(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            $cuserId = $request->input('cuserId', '');
            if(empty($userId) || empty($cuserId)){
                return response()->json(['success'=>false,'code'=>4001,'message'=>'必填参数不能为空']);
            }
            $setting = DB::table('diamond_setting')->first();
            $res = DB::table('users')->where('id','=',$cuserId)->first();
            $res->country_name = DB::table('base_country')->where('id','=',$res->position_country)->value('name');
            $res->province_name = DB::table('base_province')->where('code','=',$res->position_province)->value('name');
            $res->city_name = DB::table('base_city')->where('code','=',$res->position_city)->value('name');
            $res->area_name = DB::table('base_area')->where('code','=',$res->position_area)->value('name');
            $res->diamondInfo = $setting;
            $res->diamondInfo->login = $res->today_login_diamonds;
            $res->isFriend = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$cuserId],['is_del','=','2']])->count();
            $res->fnote = '';
            if($res->isFriend == 1){
                $res->fnote = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$cuserId],['is_del','=','2']])->value('fnote');
            }
            $formId = DB::table('users_formid')->where([['users_id','=',$res->id],['is_use','=','2']])->value('form_id');
            //发送注册消息
            if($res->is_send == 2 && $formId){
                //发送注册消息
                if(self::SendTemplate($res->id,3,'【注册成功】钻⽯奖励',$setting->register.'💎','注册成功：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i")) == 1004){
                    self::SendTemplate($res->id,3,'【注册成功】钻⽯奖励',$setting->register.'💎','注册成功：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i"));
                }
                //发送邀请人消息
                if($res->inviter_id){
                    if(self::SendTemplate($res->inviter_id,3,'【邀请新⽤户】钻⽯奖励',$setting->invite_new_users.'💎','邀请新⽤户：您成功邀请到「'.$res->nick_name.'」',date("m-d H:i")) == 1004){
                        self::SendTemplate($res->inviter_id,3,'【邀请新⽤户】钻⽯奖励',$setting->invite_new_users.'💎','邀请新⽤户：您成功邀请到「'.$res->nick_name.'」',date("m-d H:i"));
                    }
                }
                $binviterId = DB::table('users')->select('id','nick_name')->where('id','=',$res->inviter_id)->first();
                //发送邀请人的邀请人消息
                if(!empty($binviterId)){
                    if(self::SendTemplate($binviterId->id,3,'【我邀请的⼈成功邀请新⽤户】奖励',$setting->invite_new_new_users.'💎','我邀请的⼈成功邀请新⽤户：您邀请的「'.$res->nick_name.'」成功邀请了新用户',date("m-d H:i")) == 1004){
                        self::SendTemplate($binviterId->id,3,'【我邀请的⼈成功邀请新⽤户】奖励',$setting->invite_new_new_users.'💎','我邀请的⼈成功邀请新⽤户：您邀请的「'.$res->nick_name.'」成功邀请了新用户',date("m-d H:i"));
                    }
                }
                //修改发送消息
                DB::table('users')->where('id','=',$res->id)->update(array('is_send'=>1));
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 设置个人信息
     *
     * @param  Request
     * @return Response
     */
    public function saveUser(Request $request)
    {
        try{
//            echo self::wxToOss('https://wx.qlogo.cn/mmopen/vi_32/ibhEXmArJpARzTWHlxylQooxtO45MnS9AtBlZiaHqG1IWBDaX3giacbC3OfuecBaotVCia8rS3w95fYCDsIP5u3HibA/132');
//            exit;
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4002,'message'=>'必填参数不能为空']);
            }
            $uId = $request->input('uId', '');
            $headPic = $request->input('headPic', '');
            $nickName = $request->input('nickName', '');
            $wechatNumber = $request->input('wechatNumber', '');
            $phone = $request->input('phone', '');
            $describe = $request->input('describe', '');
            $country = $request->input('country', '');
            $province = $request->input('province', '');
            $city = $request->input('city', '');
            $area = $request->input('area', '');
            if(!empty($uId)){
                $data['u_id'] = $uId;
                $isUid = DB::table('users')->where('u_id',$data['u_id'])->value('id');
                //校验uid是否重复
                if($isUid){
                    return response()->json(['success'=>false,'code'=>4003,'message'=>'帮办ID已存在']);
                }
            }
            if(!empty($headPic)){
                $data['head_pic'] = self::wxToOss($headPic);
                $data['share_pic'] = self::synthesis($headPic);
            }
            if(!empty($nickName)){
                $data['nick_name'] = $nickName;
            }
            if(!empty($wechatNumber)){
                $data['wechat_number'] = $wechatNumber;
            }
            if(!empty($phone)){
                $data['phone'] = $phone;
            }
            if(!empty($describe)){
                $data['shop_describe'] = $describe;
            }
            if(!empty($country)){
                $data['position_country'] = $country;
            }
            if(!empty($province)){
                $data['position_province'] = $province;
            }
            if(!empty($city)){
                $data['position_city'] = $city;
            }
            if(!empty($area)){
                $data['position_area'] = $area;
            }
            $data['last_update_time'] = time();
            $res = DB::table('users')->where('id',$userId)->update($data);
            if($res){
                //判断资料是否完整，完整后添加注册获得钻石
                $info = DB::table('users')->where('id',$userId)->first();
                $perfectInformation = DB::table('diamond_use')->where([['users_id','=',$userId],['diamond_type','=',2]])->value('id');
                if(!$perfectInformation && !empty($info->u_id) && !empty($info->head_pic) && !empty($info->nick_name) && !empty($info->wechat_number) && !empty($info->phone) && !empty($info->shop_describe)){
                    //追加完善资料钻石
                    $diamond = DB::table('diamond_setting')->value('perfect_information');
                    $saveData['diamonds'] = floatval($info->diamonds)+floatval($diamond);;
                    $insertData['users_id'] = $userId;
                    $insertData['diamond'] = $diamond;
                    $insertData['diamond_type'] = 2;
                    $insertData['create_time'] = time();
                    DB::beginTransaction();
                    $saveDiamond = DB::table('users')->where('id',$userId)->update($saveData);
                    $insertDiamond = DB::table('diamond_use')->insert($insertData);
                    if($saveDiamond && $insertDiamond){
                        DB::commit();
                        if(self::SendTemplate($userId,3,'【完善资料】钻⽯奖励',$diamond.'💎','完善资料：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i")) == 1004){
                            self::SendTemplate($userId,3,'【完善资料】钻⽯奖励',$diamond.'💎','完善资料：钻⽯已经到账，试试使⽤钻⽯让朋友帮你找货吧',date("m-d H:i"));
                        }
                    }else{
                        DB::rollBack();
                    }
                }
                return response()->json(['success'=>true,'code'=>1000,'message'=>'修改成功']);
            }else{
                return response()->json(['success'=>false,'code'=>4004,'message'=>'修改失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }


    //微信头像保存阿里OSS
    public function wxToOss($path){
        $urlInfo = parse_url($path);
        if($urlInfo['host'] !== 'wx.qlogo.cn'){
            return $path;
        }
        $info = file_get_contents($path);
        $bpath = './uploads/'.time().round(000000,999999).'.png';
        file_put_contents($bpath,$info);
        $fileName = str_random(5) . time() .date('ymd') . '.png';
        //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
        $pathName = date('Y-m/d').'/'.$fileName;
        //上传图片到阿里云OSS
        OSS::publicUpload('doitforyou', $pathName, $bpath, ['ContentType' => 'image/png']);
        //获取上传图片的Url链接
        $url = OSS::getPublicObjectURL('doitforyou', $pathName);
        unlink($bpath);
        return $url;
    }

    //图片缩放
    public function imagecropper($source_path, $target_width, $target_height)
    {
        $source_info   = getimagesize($source_path);
        $source_width  = $source_info[0];
        $source_height = $source_info[1];
        $source_mime   = $source_info['mime'];
        $source_ratio  = $source_height / $source_width;
        $target_ratio  = $target_height / $target_width;

        // 源图过高
        if ($source_ratio > $target_ratio)
        {
            $cropped_width  = $source_width;
            $cropped_height = $source_width * $target_ratio;
            $source_x = 0;
            $source_y = ($source_height - $cropped_height) / 2;
        }
        // 源图过宽
        elseif ($source_ratio < $target_ratio)
        {
            $cropped_width  = $source_height / $target_ratio;
            $cropped_height = $source_height;
            $source_x = ($source_width - $cropped_width) / 2;
            $source_y = 0;
        }
        // 源图适中
        else
        {
            $cropped_width  = $source_width;
            $cropped_height = $source_height;
            $source_x = 0;
            $source_y = 0;
        }

        switch ($source_mime)
        {
            case 'image/gif':
                $source_image = imagecreatefromgif($source_path);
                break;

            case 'image/jpeg':
                $source_image = imagecreatefromjpeg($source_path);
                break;

            case 'image/png':
                $source_image = imagecreatefrompng($source_path);
                break;

            default:
                return false;
                break;
        }

        $target_image  = imagecreatetruecolor($target_width, $target_height);
        $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

        // 图片裁剪
        imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
        // 图片缩放
        imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

        $path = './uploads/'.time().round(000000,999999).'.png';
        imagepng($target_image,$path);
        imagedestroy($source_image);
        imagedestroy($target_image);
        imagedestroy($cropped_image);
        return $path;
//        header('Content-Type: image/jpeg');
//        imagejpeg($target_image);
    }

    //图片合成
    public function synthesis($headPic){
        //判断当前地址是微信地址还是阿里地址
        $urlInfo = parse_url($headPic);
        if($urlInfo['host'] !== 'wx.qlogo.cn'){
            $headPic = $headPic.'?x-oss-process=style/original';
        }
        $fyuan = self::imagecropper($headPic,220,220);
        $radius = 110;
        $ext = file_get_contents($fyuan);
        $src_img = imagecreatefromstring($ext);
        $wh = getimagesize($fyuan);
        $w  = $wh[0];
        $h  = $wh[1];
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r = $radius; //圆 角半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (($x >= $radius && $x <= ($w - $radius)) || ($y >= $radius && $y <= ($h - $radius))) {
                    //不在四角的范围内,直接画
                    imagesetpixel($img, $x, $y, $rgbColor);
                } else {
                    //在四角的范围内选择画
                    //上左
                    $y_x = $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //上右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下左
                    $y_x = $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                    //下右
                    $y_x = $w - $r; //圆心X坐标
                    $y_y = $h - $r; //圆心Y坐标
                    if (((($x - $y_x) * ($x - $y_x) + ($y - $y_y) * ($y - $y_y)) <= ($r * $r))) {
                        imagesetpixel($img, $x, $y, $rgbColor);
                    }
                }
            }
        }
        $path_2 = './uploads/'.time().round(000000,999999).'.png';
        imagepng($img,$path_2);
        imagedestroy($img);
        $path_1 = "./img/background.png";
        //将人物和装备图片分别取到两个画布中
        $image_1 = imagecreatefrompng($path_1);
        switch (getimagesize($path_2)['mime']) {
            case 'image/png':
                $image_2 = imagecreatefrompng($path_2);
                break;
            case 'image/gif':
                $image_2 = imagecreatefromgif($path_2);
                break;
            case 'image/jpeg':
                $image_2 = imagecreatefromjpeg($path_2);
                break;
            case 'image/jpg':
                $image_2 = imagecreatefromjpeg($path_2);
                break;
            default:
                exit("上传文件格式不正确");
                break;
        }
        //创建一个和人物图片一样大小的真彩色画布（ps：只有这样才能保证后面copy装备图片的时候不会失真）
        $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));
        //为真彩色画布创建白色背景，再设置为透明
        $color = imagecolorallocate($image_3, 255, 255, 255);
        imagefill($image_3, 0, 0, $color);
        imageColorTransparent($image_3, $color);
        //首先将人物画布采样copy到真彩色画布中，不会失真
        imagecopyresampled($image_3,$image_1,0,0,0,0,imagesx($image_1),imagesy($image_1),imagesx($image_1),imagesy($image_1));
        //再将装备图片copy到已经具有人物图像的真彩色画布中，同样也不会失真
        imagecopymerge($image_3,$image_2, 202, 255,0,0,imagesx($image_2),imagesy($image_2), 100);
        //将画布保存到指定的gif文件
//        header("content-type:image/png");
//        imagepng($image_3);exit;
        $path_3 = './uploads/'.time().round(000000,999999).'.png';
        imagepng($image_3,$path_3);
        imagedestroy($image_1);
        imagedestroy($image_2);
        imagedestroy($image_3);
        $fileName = str_random(5) . time() .date('ymd') . '.png';
        //拼接上传的文件夹路径(按照日期格式1810/17/xxxx.jpg)
        $pathName = date('Y-m/d').'/'.$fileName;
        //上传图片到阿里云OSS
        OSS::publicUpload('doitforyou', $pathName, $path_3, ['ContentType' => 'image/png']);
        //获取上传图片的Url链接
        $url = OSS::getPublicObjectURL('doitforyou', $pathName);
//        unlink($fyuan);
//        unlink($path_2);
        unlink($path_3);
        return $url;
    }

    /**
     * 搜索用户
     *
     * @param  Request
     * @return Response
     */
    public function searchUser(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4005,'message'=>'必填参数不能为空']);
            }
            $keyword = $request->input('keyword', '');
            $status = $request->input('status', '');
            $where[] = ['users.is_del','=',2];
            if($status == 'add'){
                if(!empty($keyword)){
                    $res = DB::table('users')->select('users.id','users.nick_name','users.head_pic','users.shop_describe')
                        ->where($where)->where(function ($query) use ($keyword) {
                            $query->orWhere('users.nick_name','like','%'.$keyword.'%')
                                ->orWhere('users.wechat_number','like','%'.$keyword.'%')
                                ->orWhere('users.phone','like','%'.$keyword.'%')
                                ->orWhere('users.shop_describe','like','%'.$keyword.'%');
                        })->get();
                }else{
                    $res = DB::table('users')->select('users.id','users.nick_name','users.head_pic','users.shop_describe')
                        ->where($where)->get();
                }

                if(!empty($res)){
                    //判断是否是好友
                    foreach($res as $k=>$v){
                        $isUser = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$v->id],['is_del','=',2]])->value('id');
                        if($isUser){
                            $v->fnote = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$v->id],['is_del','=',2]])->value('fnote');
                            $v->isUser = 1;
                        }else{
                            $v->fnote = '';
                            $v->isUser = 0;
                        }
                    }
                }
            }else{
                $where[] = ['users_relationship.is_del','=',2];
                $where[] = ['users_relationship.users_id','=',$userId];
                if(!empty($keyword)){
                    $res = DB::table('users_relationship')->join('users', 'users_relationship.friends_id', '=', 'users.id')
                        ->select('users.id','users.nick_name','users.head_pic','users.shop_describe')
                        ->where($where)->where(function ($query) use ($keyword) {
                            $query->orWhere('users.nick_name','like','%'.$keyword.'%')
                                ->orWhere('users.wechat_number','like','%'.$keyword.'%')
                                ->orWhere('users.phone','like','%'.$keyword.'%')
                                ->orWhere('users.shop_describe','like','%'.$keyword.'%')
                                ->orWhere('users_relationship.fnote','like','%'.$keyword.'%');
                        })->get();
                }else{
                    $res = DB::table('users_relationship')->join('users', 'users_relationship.friends_id', '=', 'users.id')
                        ->select('users.id','users.nick_name','users.head_pic','users.shop_describe')
                        ->where($where)->get();
                }

                if(!empty($res)){
                    //判断是否是好友
                    foreach($res as $k=>$v){
                        $isUser = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$v->id],['is_del','=',2]])->value('id');
                        if($isUser){
                            $v->fnote = DB::table('users_relationship')->where([['users_id','=',$userId],['friends_id','=',$v->id],['is_del','=',2]])->value('fnote');
                            $v->isUser = 1;
                        }else{
                            $v->fnote = '';
                            $v->isUser = 0;
                        }
                    }
                }
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 好友list
     *
     * @param  Request
     * @return Response
     */
    public function listUser(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4006,'message'=>'必填参数不能为空']);
            }
            $where[] = ['users.is_del','=',2];
            $where[] = ['users_relationship.is_del','=',2];
            $where[] = ['users_relationship.users_id','=',$userId];
            $res = DB::table('users_relationship')->join('users', 'users_relationship.friends_id', '=', 'users.id')
                ->select('users.nick_name','users.head_pic','users.shop_describe','users_relationship.friends_id','users_relationship.fnote')
                ->orderBy(DB::raw('convert(users.nick_name using gbk)'))->where($where)->get()->Toarray();
            $data=[];
            if(!empty($res)){
                foreach ($res as $k => $v) {
                    $v->chart=self::getFirstChart($v->nick_name);
                }
                foreach ($res as $k => $v) {
                    if ( empty( $data[ $v->chart ] ) ) {
                        $data[ $v->chart ]=[];
                    }
                    $data[ $v->chart ][]=$v;
                    unset($v->chart);
                }
                ksort($data);
            }
            return response()->json(['success'=>true,'code'=>1000,'message'=>$data]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }
    /**
     * 返回取汉字的第一个字的首字母
     * @param  [type] $str [string]
     * @return [type]      [strind]
     */
    public function getFirstChart($str){
        if( empty($str) ){
            return '';
        }
        $char=ord($str[0]);
        if( $char >= ord('A') && $char <= ord('z') ){
            return strtoupper($str[0]);
        }
        $str = mb_substr($str,0,1);

        $regex = "/\/|\～|\，|\。|\！|\？|\“|\”|\【|\】|\『|\』|\：|\；|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
        if(preg_match($regex,$str)){
            return '#';
        }
        $s1=iconv('UTF-8','GB2312',$str);
        $s2=iconv('GB2312','UTF-8',$s1);
        $s=$s2==$str?$s1:$str;
        $asc=ord($s{0})*256+ord($s{1})-65536;
        if($asc>=-20319&&$asc<=-20284) return 'A';
        if($asc>=-20283&&$asc<=-19776) return 'B';
        if($asc>=-19775&&$asc<=-19219) return 'C';
        if($asc>=-19218&&$asc<=-18711) return 'D';
        if($asc>=-18710&&$asc<=-18527) return 'E';
        if($asc>=-18526&&$asc<=-18240) return 'F';
        if($asc>=-18239&&$asc<=-17923) return 'G';
        if($asc>=-17922&&$asc<=-17418) return 'H';
        if($asc>=-17417&&$asc<=-16475) return 'J';
        if($asc>=-16474&&$asc<=-16213) return 'K';
        if($asc>=-16212&&$asc<=-15641) return 'L';
        if($asc>=-15640&&$asc<=-15166) return 'M';
        if($asc>=-15165&&$asc<=-14923) return 'N';
        if($asc>=-14922&&$asc<=-14915) return 'O';
        if($asc>=-14914&&$asc<=-14631) return 'P';
        if($asc>=-14630&&$asc<=-14150) return 'Q';
        if($asc>=-14149&&$asc<=-14091) return 'R';
        if($asc>=-14090&&$asc<=-13319) return 'S';
        if($asc>=-13318&&$asc<=-12839) return 'T';
        if($asc>=-12838&&$asc<=-12557) return 'W';
        if($asc>=-12556&&$asc<=-11848) return 'X';
        if($asc>=-11847&&$asc<=-11056) return 'Y';
        if($asc>=-11055&&$asc<=-10247) return 'Z';
        return null;
    }


    /**
     * 好友申请列表
     *
     * @param  Request
     * @return Response
     */
    public function applyListUser(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4007,'message'=>'必填参数不能为空']);
            }
            $where[] = ['users.is_del','=',2];
            $where[] = ['users_apply.is_del','=',2];
            $where[] = ['users_apply.users_id','=',$userId];
            $res = DB::table('users_apply')->join('users', 'users_apply.friends_id', '=', 'users.id')
                ->select('users.nick_name','users.head_pic','users.shop_describe','users_apply.note','users_apply.friends_id','users_apply.status')
                ->where($where)->get();
            $saveData['is_read'] = 1;
            DB::table('users_apply')->where('users_id','=',$userId)->update($saveData);
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 添加好友
     *
     * @param  Request
     * @return Response
     */
    public function addUser(Request $request)
    {
        try{
            $data['users_id'] = $request->input('userId', '');
            $data['friends_id'] = $request->input('friendsId', '');
            $note = $request->input('note', '');
            if(empty($data['users_id']) || empty($data['friends_id'])){
                return response()->json(['success'=>false,'code'=>4008,'message'=>'必填参数不能为空']);
            }
            $data['create_time'] = time();
            $aData['users_id'] = $data['friends_id'];
            $aData['friends_id'] = $data['users_id'];
            $aData['note'] = $note;
            $aData['create_time'] = time();
            //校验当前好友是否已存在,是否删除
//            $setting = DB::table('diamond_setting')->first();
            DB::beginTransaction();
            $addDiamond = true;
            $useDiamond = true;
            $isId = DB::table('users_relationship')->where([['users_id','=',$data['users_id']],['friends_id','=',$data['friends_id']]])->value('is_del');
            if($isId == 2){
                return response()->json(['success'=>false,'code'=>4009,'message'=>'好友关系已存在']);
            }elseif ($isId == 1){
                //已删除，不添加钻石
                $addg = DB::table('users_relationship')->where([['users_id','=',$data['users_id']],['friends_id','=',$data['friends_id']]])->update(array('is_del'=>2,'create_time'=>time()));
            }else{
                //新添加好友添加钻石
                $addg = DB::table('users_relationship')->insert($data);
//                //添加钻石及记录
//                $addDiamond = DB::table('users')->where('id','=',$data['friends_id'])->increment('diamonds', $setting->b_add_friends);
//                $useDiamond = DB::table('diamond_use')->insert(array('users_id'=>$data['friends_id'],'diamond'=>$setting->b_add_friends,'diamond_type'=>4,'create_time'=>time()));
            }
            //判断当前好友申请是否存在，存在变状态
            if(DB::table('users_apply')->where([['friends_id','=',$data['users_id']],['users_id','=',$data['friends_id']]])->value('id')){
                $applyData['status'] = 1;
                $applyData['note'] = $note;
                $applyData['is_del'] = 2;
                $applyData['is_read'] = 2;
                $applyData['create_time'] = time();
                $applyData['agree_time'] = '';
                $adda = DB::table('users_apply')->where([['friends_id','=',$data['users_id']],['users_id','=',$data['friends_id']]])->update($applyData);
            }else{
                $adda = DB::table('users_apply')->insert($aData);
            }
            if($adda && $addg && $addDiamond && $useDiamond){
                DB::commit();
                //发送好友邀请消息
                $nickName = DB::table('users')->where('id','=',$data['users_id'])->value('nick_name');
                if(self::SendTemplate($data['friends_id'],2,'「'.$nickName.'」申请加你为好友',$nickName,'你好我是'.$nickName,date("m-d H:i"),$data['users_id']) == 1004){
                    self::SendTemplate($data['friends_id'],2,'「'.$nickName.'」申请加你为好友',$nickName,'你好我是'.$nickName,date("m-d H:i"),$data['users_id']);
                }
                return response()->json(['success'=>true,'code'=>1000,'message'=>'添加成功']);
            }else{
                DB::rollBack();
                return response()->json(['success'=>false,'code'=>4010,'message'=>'添加失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 删除好友
     *
     * @param  Request
     * @return Response
     */
    public function delUser(Request $request)
    {
        try{
            $usersId = $request->input('userId', '');
            $friendsId = $request->input('friendsId', '');
            if(empty($usersId) || empty($friendsId)){
                return response()->json(['success'=>false,'code'=>4011,'message'=>'必填参数不能为空']);
            }
            $data['is_del'] = 1;
            $data['del_time'] = time();
            $where[] = ['users_id','=',$usersId];
            $where[] = ['friends_id','=',$friendsId];
            $res = DB::table('users_relationship')->where($where)->update($data);
            if($res){
                return response()->json(['success'=>true,'code'=>1000,'message'=>'删除成功']);
            }else{
                return response()->json(['success'=>false,'code'=>4012,'message'=>'删除失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }


    /**
     * 同意/拒绝好友添加
     *
     * @param  Request
     * @return Response
     */
    public function agreeAddUser(Request $request)
    {
        try{
            $usersId = $request->input('userId', '');
            $friendsId = $request->input('friendsId', '');
            $status = $request->input('status', 1);
            if(empty($usersId) || empty($friendsId)){
                return response()->json(['success'=>false,'code'=>4013,'message'=>'必填参数不能为空']);
            }
            $saveData['status'] = $status;
            $saveData['agree_time'] = time();
            //判断当前状态是否是待审核
            $isStatus = DB::table('users_apply')->where([['users_id','=',$usersId],['friends_id','=',$friendsId]])->value('status');
            if($isStatus != 1){
                return response()->json(['success'=>false,'code'=>4014,'message'=>'当前状态错误']);
            }
            //校验当前好友是否已存在，修改当前状态并返回
            $isId = DB::table('users_relationship')->where([['users_id','=',$usersId],['friends_id','=',$friendsId],['is_del','=',2]])->value('id');
            if($isId){
                DB::table('users_apply')->where([['users_id','=',$usersId],['friends_id','=',$friendsId],['is_del','=',2]])->update(array('status'=>$status));
                return response()->json(['success'=>true,'code'=>1000,'message'=>'操作成功']);
            }
            //同意添加好友关系
            $setting = DB::table('diamond_setting')->first();
            $agree = true;
            $addDiamond = true;
            $useDiamond = true;
            DB::beginTransaction();
            $update = DB::table('users_apply')->where([['users_id','=',$usersId],['friends_id','=',$friendsId]])->update($saveData);
            if($status == 2){
                $isUser = DB::table('users_relationship')->where([['users_id','=',$usersId],['friends_id','=',$friendsId]])->value('id');
                //添加申请记录及增加钻石
                if($isUser){
                    $agree = DB::table('users_relationship')->where([['users_id','=',$usersId],['friends_id','=',$friendsId]])->update(array('is_del'=>2));
                }else{
                    $agree = DB::table('users_relationship')->insert(array('users_id'=>$usersId,'friends_id'=>$friendsId,'create_time'=>time()));
                }
                //判断是否是取消关注过，如果第一次互相关注增加钻石
                if(DB::table('diamond_use')->where([['users_id','=',$friendsId],['diamond_type','=',4]])->value('id')){
                    $addDiamond = DB::table('users')->where('id','=',$friendsId)->increment('diamonds', $setting->b_add_friends);
                    $useDiamond = DB::table('diamond_use')->insert(array('users_id'=>$friendsId,'diamond'=>$setting->b_add_friends,'diamond_type'=>4,'create_time'=>time()));
                    $isBadd = array(
                        'userId'=>$friendsId,
                        'diamonds'=>$setting->b_add_friends,
                        'nick_name'=>DB::table('users')->where('id','=',$usersId)->value('nick_name')
                    );
                }
            }
            if($update && $agree && $addDiamond && $useDiamond){
                DB::commit();
                //发送被加好友消息
                if(!empty($isBadd)){
                    if(self::SendTemplate($isBadd['userId'],3,'【被加好友】钻⽯奖励',$isBadd['diamonds'].'💎','被加好友：「'.$isBadd['nick_name'].'」加你为好友',date("m-d H:i")) == 1004){
                        self::SendTemplate($isBadd['userId'],3,'【被加好友】钻⽯奖励',$isBadd['diamonds'].'💎','被加好友：「'.$isBadd['nick_name'].'」加你为好友',date("m-d H:i"));
                    }
                }
                return response()->json(['success'=>true,'code'=>1000,'message'=>'操作成功']);
            }else{
                DB::rollBack();
                return response()->json(['success'=>false,'code'=>4016,'message'=>'操作失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
 * 钻石消费列表
 *
 * @param  Request
 * @return Response
 */
    public function diamondList(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4017,'message'=>'必填参数不能为空']);
            }
            //当前页码
            $pageNumber = $request->input('pageNumber', 1);
            //每页显示数量
            $pageSize = $request->input('pageSize', 10);
            $pyl = ($pageNumber-1)*$pageSize;
            $res = DB::table('diamond_use')->where('users_id','=',$userId)->orderBy('id', 'desc')->skip($pyl)->take($pageSize)->get();
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 钻石消费列表
     *
     * @param  Request
     * @return Response
     */
    public function applyNum(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            if(empty($userId)){
                return response()->json(['success'=>false,'code'=>4017,'message'=>'必填参数不能为空']);
            }
            $where[] = ['users_id','=',$userId];
            $where[] = ['is_del','=',2];
            $where[] = ['status','=',1];
            $res = DB::table('users_apply')->where($where)->count();
            return response()->json(['success'=>true,'code'=>1000,'message'=>$res]);
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }

    /**
     * 修改好友备注
     *
     * @param  Request
     * @return Response
     */
    public function friendNote(Request $request)
    {
        try{
            $userId = $request->input('userId', '');
            $friendsId = $request->input('friendsId', '');
            $note = $request->input('note', '');
            if(empty($userId) || empty($friendsId) || empty($note)){
                return response()->json(['success'=>false,'code'=>4018,'message'=>'必填参数不能为空']);
            }
            $where[] = ['users_id','=',$userId];
            $where[] = ['friends_id','=',$friendsId];
            $res = DB::table('users_relationship')->where($where)->update(array('fnote'=>$note));
            if($res !== false){
                return response()->json(['success'=>true,'code'=>1000,'message'=>'修改成功']);
            }else{
                return response()->json(['success'=>true,'code'=>4019,'message'=>'修改失败']);
            }
        }catch (\Exception $e){
            return response()->json(['success'=>false,'code'=>9999,'message'=>$e->getMessage()]);
        }
    }
}
